var roleManage = function() {

    var init_datepicker = function () {
        // 开始时间
        $('#startTime').datepicker({
            language:"zh-CN",
            todayBtn : "linked",
            autoclose : true,
            todayHighlight : true,
            startDate : new Date()
        }).on('changeDate',function(e){
            var startTime = e.date;
            $('#endTime').datepicker('setStartDate', startTime);
        });
        // 结束时间：
        $('#endTime').datepicker({
            language:"zh-CN",
            todayBtn : "linked",
            autoclose : true,
            todayHighlight : true,
            startDate : new Date()
        }).on('changeDate',function(e){
            var endTime = e.date;
            $('#startTime').datepicker('setEndDate', endTime);
        });
    };

	var storeId = $('#store').find("option:selected").val();
	var _init = function() {
		var  table = $('#table_role');
		table.dataTable({
			"processing" : true,			
			serverSide : true,// 开启服务器模式
			"ajax" : {
				url : list_url,  // 列表查询
				data:{'storeId':storeId}
			},
			"autoWidth" : false,
			"columns" : [
				{
					"width" : "15%",
					"data" : "name",
					"render" : function(data, type, row, meta) {
						return data;
					}
				},		
				{
					"width" : "5%",
					"data" : "value2",
					"render" : function(data, type, row, meta) {
						return data/100;
					}
				},
				{
					"width" : "10%",
					"data" : "getCond",
					"render" : function(data, type, row, meta) {
						if(data=='1'){
							return "手动领取"
						}else if(data=='2'){
							return "完成手机绑定"
						}else if(data=='3'){
							return "完成订单消费"
						}else if(data=='4'){
							return "完成分享好友"
						}else{
							return "--"
						}
					}
				},
				{
					"width" : "10%",
					"data" : "type",
					"render" : function(data, type, row, meta) {
						if(data=='无限制'){
							return "无限制"
						}else if(data=='消费满减'){
							return "消费满"+row.value1/100+"元"
						}else{
							return "";
						}
					}
				},
				{
					"width" : "5%",
					"data" : "totalCount",
					"render" : function(data, type, row, meta) {
						if(row.isLimit == 1) {
							return '总量不限';
						} else {
							return data;
						}
					}
				},
				{
					"width" : "5%",
					"data" : "receiveCount",
				},
				{
					"width" : "20%",
					 "data": "null",
					"render" : function(data, type, row, meta) {
						var etime = timestampToTime2(row.endTime);
						var stime = timestampToTime2(row.startTime);
						return stime + "  至  "+etime;
					}
				},
				{
					"width" : "13%",
					"data":"createDate",
					"render" : function(data, type, row, meta) {
						//return timestampToTime(data);
						return moment(data).format('YYYY-MM-DD HH:mm');
					}
				},
				{
					"width" : "5%",
					 "data": "null",
					"render" : function(data, type, row, meta) {
						var curTime = new Date();
				        curTime = Date.parse(curTime)/1000;
				        if(row.endTime < curTime){
				    		return "过期失效";
				        }else if(row.startTime > curTime){
				        	return "还未开始";
				        } else{
				        	return "使用中";
				        }
					}
				},
				{
					"width" : "15%",
					"render" : function(data, type, row, meta) {
						return '<button type="button" class="btn btn-info btn-xs btn_edit_coupon">编辑</button>'+
							'<button type="button" class="btn btn-danger btn-xs btn_del_role">删除</button>'+
							'<button type="button" class="btn bg-purple btn-xs btn_record_coupon">领取记录</button>';
					}
				} 
			],
			"language" : {
				"lengthMenu" : "每页显示 _MENU_ 条记录",
				"emptyTable" : "暂无数据记录",
				"info" : "显示 _START_ 至 _END_ 条数据，共 _TOTAL_ 条记录！",
				"zeroRecords" : "没有搜索到匹配记录",
				"infoEmpty" : "暂无数据",
				"infoFiltered" : "",
				"processing" : "数据加载中"
			},
			"destroy" : true,
			"pageLength" : 10,
            "stateSave": true,
            "stateSaveParams": function (settings, data) {
                var search = data.search.search;
                if(search){
                    var arr = $.parseJSON(search);
                    for(var key in arr){
                        $("#searchForm input[name='"+key+"']").val(arr[key]);
                        $("#searchForm select[name='"+key+"']").val(arr[key]);
                    }
                }
            },
			"order" : [ [ 7, "desc" ] ],
			"columnDefs" : [ {
				"orderable" : false,
				"targets" : [ 0,2,3,6,8,9]
			} ],
			"dom" : "<'row'<'.col-md-6 col-sm-12'><'col-md-6 col-sm-12'>r>"
					+ "<t>" + "<'table_b relative'<'col-md-5'i><'col-md-7'>lp>",
			"fnInitComplete" : function() {
			}
		});

		// 删除
		table.on('click', '.btn_del_role', function(event) {
			var oData_arr = table.DataTable().rows($(this).parents("tr")).data(); // 操作行对象
			var _id = oData_arr[0].id;
			bootbox.dialog({
				message : "确定要删除?",
				title : "提示",
				buttons : {
					cancel : {
						label : "取消",
						className : "btn dark btn-outline"
					},
					success : {
						label : "确定",
						className : "btn green",
						callback : function() {
							$.ajax({
                                url : del_url,
                                type : 'delete',
                                dataType : 'json',
                                contentType:"application/json; charset=utf-8",
                                data : JSON.stringify({ id:_id}),
                                async: false
                            }).done(function(data) {
                                if (data.status === '1') {
                                    //table.DataTable().ajax.reload();
                                    table.DataTable().draw(false);
                                } else if (data.status === '2') {
                                    layer.msg(data.message);
                                }
                            });
						}
					}
				}
			});
		});

		//编辑
		table.on('click', '.btn_edit_coupon', function(event) {
			var oData_arr = table.DataTable().rows($(this).parents("tr")).data(); // 操作行对象
	        var _id = oData_arr[0].id;
	        var _storeId = oData_arr[0].storeId;
	        window.location.href = edit_url + "?id="+ encodeURIComponent(_id) + '&storeId='+_storeId;
		});

		//查看领取记录
		table.on('click', '.btn_record_coupon', function(event) {
			var oData_arr = table.DataTable().rows($(this).parents("tr")).data(); // 操作行对象
	        var _id = oData_arr[0].id;
	        var _storeId = oData_arr[0].storeId;
	        window.location.href = useList_url + "?id="+ encodeURIComponent(_id);
		});
			
		//添加新代金券
		$("#add_coupon").on("click",function(){
			window.location.href = add_url + '?storeId='+storeId;
		});
		
		// 领取方式切换  --begin
		var getCond = $("input[name='getCond']:checked").parent("label").index();
	    if(getCond==-1)
	    	getCond=0;
	    $("input[name='getCond']").eq(getCond).prop('checked', 'true');
		$(".xqClass").eq(getCond).show().siblings(".xqClass").hide();;
		
		$(".changeGetCond label").click(function(){
			var ln = $(this).index();
			$(".xqClass").eq(ln).show().siblings(".xqClass").hide();
		});
		// 领取方式切换  --end
	};

	return {
		init : function() {
            init_datepicker();
			_init();
		}
	};

}();

$(function() {
	roleManage.init();
});

function timestampToTime(timestamp) {
    var date = new Date(timestamp * 1000);
    Y = date.getFullYear() + '-';
    M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
    D = date.getDate() + ' ';
    h = checkTime(date.getHours()) + ':';
    m = checkTime(date.getMinutes()) + ':';
    s = checkTime(date.getSeconds());
    return Y+M+D+h+m+s;
}

function timestampToTime2(timestamp) {
    var date = new Date(timestamp * 1000);
    Y = date.getFullYear() + '-';
    M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
    D = date.getDate() + ' ';
    return Y+M+D;
}

function checkTime(i){  //补足前导0
    if (i<10)
        i="0" + i
    return i
}

function beback(){
	window.location.href = index_url;
}

function changeStore(e) {  //切换门店
    var id = e.value;
    window.location.href=index_url+'?storeId='+id;
}

$('#form1 .form-control').change(function(event){  //根据状态查询代金券列表
    var status =   $("#form1 select[name='status']").val();
    var param={"status":status};
    $('#table_role').DataTable().search(JSON.stringify(param)).draw();   
});

//选择时段控制
$("div.datatime .datatimebox input").each(function(){
    $(this).on('click', function(e) {
    	var test = '';
    	$('#modal_new_role').find('input[name="useWeek"]:checked').each(function(){
    		test = test + $(this).val() + ',';
    	});
    	if(test.length == 0) {  //未选择时段
            layer.msg('您还未选择时段，仅填写时间无效');
    	}
	});
});

var storeId = $('#modal_new_role').find("input[name='storeId']").val();
// 添加/编辑保存
$('#save').click(function() {
	var _data = $("#modal_new_role").serializeObject();

	if (!mdTool.validate(_data.name, 'require')) {
		layer.msg('请输入名称');
		$('#modal_new_role').find('input[name="name"]').focus();
		return;
	}
    if (_data.name.length > 60) {
        layer.msg('名称最长为60个字符');
        $('#modal_new_role').find('input[name="name"]').focus();
        return;
    }
	if (!mdTool.validate(_data.value2, 'require')) {
		layer.msg('请输入面值金额');
		$('#modal_new_role').find('input[name="value2"]').focus();
		return;
	}
    /*if(!mdTool.validate(_data.value2,'two') || _data.value2 == 0){
        layer.msg('面值金额应大于0，且小数点后只有两位');
        $('#modal_new_role').find('input[name="value2"]').focus();
        return;
    }*/
    if(!mdTool.validate(_data.value2,'num')){
        layer.msg('面值金额应为非零的正整数');
        $('#modal_new_role').find('input[name="value2"]').focus();
        return;
    }
    if(_data.value2.length > 11){
        layer.msg('面值金额最长为11位');
        $('#modal_new_role').find('input[name="value2"]').focus();
        return;
    }
    if (_data.type== '消费满减'  && !mdTool.validate(_data.value1, 'require')) {
        layer.msg('请输入消费满减金额');
        $('#zhekou').focus();
        return;
    }
    /*if(!mdTool.validate(_data.value1,'two') || _data.value1 == 0){
        layer.msg('消费满减金额应大于0，且小数点后只有两位');
        $('#zhekou').focus();
        return;
    }*/
	if(_data.value1){
        if(!mdTool.validate(_data.value1,'num')){
            layer.msg('消费满减金额应为非零的正整数');
            $('#zhekou').focus();
            return;
        }
		if(parseInt(_data.value1) <= parseInt(_data.value2)){
            layer.msg('消费满减金额必须大于面值金额');
            $('#zhekou').focus();
            return false;
		}
	}
	if (!mdTool.validate(_data.startTime, 'require')) {
		layer.msg("请选择生效时间");
		return;
	}if (!mdTool.validate(_data.endTime, 'require')) {
		layer.msg("请选择过期时间");
		return;
	}
	if(_data.endTime < _data.startTime) {
		layer.msg("结束时间不能早于生效时间");
		return;
	}
    console.log(_data.dayStartTime >= _data.dayEndTime);
    if(_data.dayStartTime >= _data.dayEndTime) {
        layer.msg("结束时间段必须晚于开始时间段");
        return;
    }
	if(_data.getCond == 1){   //手动领取
		if (!mdTool.validate(_data.maxGet[0], 'require')) {
			layer.msg('请输入每人限领数量');
			$('#modal_new_role').find('input[name="maxGet"]').focus();
			return;
		}
		if(_data.maxGet[0] != 0){
            if(!mdTool.validate(_data.maxGet[0],'num')){
                layer.msg('每人限领数量为正整数');
                $('#modal_new_role').find('input[name="maxGet"]').focus();
                return;
            }
		}
		
		if(_data.isLimit1 == undefined) {
			if (!mdTool.validate(_data.totalCount[0], 'require')) {
				layer.msg('请输入代金券总量');
				$('#modal_new_role').find('input[name="totalCount"]').focus();
				return;
			}
            if(_data.totalCount[0] != 0){
                if(!mdTool.validate(_data.totalCount[0],'num')){
                    layer.msg('代金券总量为正整数');
                    $('#modal_new_role').find('input[name="totalCount"]').focus();
                    return;
                }
            }
			if( parseInt(_data.totalCount[0]) <= parseInt(_data.maxGet[0]) ) {
				layer.msg('每人限领数量不能大于等于代金券总量');
				$('#modal_new_role').find('input[name="maxGet"]').focus();
				return;
			}
		}
		_data.totalCount = _data.totalCount[0];
		_data.maxGet = _data.maxGet[0];
		_data.isLimit = _data.isLimit1 == undefined ? 2 :  _data.isLimit1;
        _data.isGetPhone = _data.isGetPhone == undefined ? 2 :  _data.isGetPhone;
		delete _data.isLimit1;
		delete _data.isLimit2;
	} else {  //完成订单消费赠送
		if (!mdTool.validate(_data.condValue1, 'require') || !mdTool.validate(_data.condValue2, 'require')) {
			layer.msg('请输入订单金额范围');
			$('#modal_new_role').find('input[name="condValue1"]').focus();
			return;
		}
        /*if(!mdTool.validate(_data.condValue1,'two') || _data.condValue1 == 0){
            layer.msg('订单金额应大于0，且小数点后只有两位');
            $('#modal_new_role').find('input[name="condValue1"]').focus();
            return;
        }*/
        if(!mdTool.validate(_data.condValue1,'num')){
            layer.msg('订单金额应为非零的正整数');
            $('#modal_new_role').find('input[name="condValue1"]').focus();
            return;
        }
        if(_data.condValue1.length > 11){
            layer.msg('订单金额最长为11位');
            $('#modal_new_role').find('input[name="condValue1"]').focus();
            return;
        }
        /*if(!mdTool.validate(_data.condValue2,'two') || _data.condValue2 == 0){
            layer.msg('订单金额应大于0，且小数点后只有两位');
            $('#modal_new_role').find('input[name="condValue2"]').focus();
            return;
        }*/
        if(!mdTool.validate(_data.condValue2,'num')){
            layer.msg('订单金额应为非零的正整数');
            $('#modal_new_role').find('input[name="condValue2"]').focus();
            return;
        }
        if(parseInt(_data.condValue2) <= parseInt(_data.condValue1)){
            layer.msg('最大金额必须大于最小金额');
            $('#modal_new_role').find('input[name="condValue2"]').focus();
            return;
        }
		if (!mdTool.validate(_data.maxGet[1], 'require')) {
			layer.msg('请输入每人限送数量');
			$('#modal_new_role').find('input[name="maxGet"]').focus();
			return;
		}
        if(_data.maxGet[1] != 0){
            if(!mdTool.validate(_data.maxGet[1],'num')){
                layer.msg('每人限送数量为正整数');
                $('#modal_new_role').find('input[name="maxGet"]').focus();
                return;
            }
        }
		
		if(_data.isLimit2 == undefined) {
			if ( !mdTool.validate(_data.totalCount[1], 'require')) {
				layer.msg('请输入赠送总量');
				$('#modal_new_role').find('input[name="totalCount"]').focus();
				return;
			}
            if(_data.totalCount[1] != 0){
                if(!mdTool.validate(_data.totalCount[1],'num')){
                    layer.msg('赠送总量为正整数');
                    $('#modal_new_role').find('input[name="totalCount"]').focus();
                    return;
                }
            }
			if( parseInt(_data.totalCount[1]) <= parseInt(_data.maxGet[1]) ) {
				layer.msg('每人限送数量不能大于等于赠送总量');
				$('#modal_new_role').find('input[name="maxGet"]').focus();
				return;
			}
		}
		_data.totalCount = _data.totalCount[1];
		_data.maxGet = _data.maxGet[1];
		_data.isLimit = _data.isLimit2 == undefined ? 2 :  _data.isLimit2;
		delete _data.isLimit1;
		delete _data.isLimit2;
	}
	// console.log(_data);
	_data.value2 = _data.value2 * 100;
	_data.value1 = _data.value1 * 100;
	_data.condValue1 = _data.condValue1 * 100;
	_data.condValue2 = _data.condValue2 * 100;
	//为避免多次重复提交，保存后先禁用，完成后启用
    $("#save").attr("disabled","disabled");
	//数据提交
	$.ajax({
        url :savePost_url,
        type : 'POST',
        dataType : 'json',
        contentType:"application/json; charset=utf-8",
        data : JSON.stringify(_data),
    }).done(function(data) {
        if(data.status === '2') {
        	("#save").removeAttr("disabled");
            layer.msg(data.message);
        } else if(data.status === '1'){
        	layer.msg('保存成功');
            location.href = index_url+'?storeId='+storeId;
        }
    });
});


$("input[type='radio']").click(function(){
	$("input[type='radio']").parent().parent().find("input[type='text']").attr("disabled","disabled");
	$("input[type='radio']:checked").parent().parent().find("input[type='text']").removeAttr("disabled");
});
